package cn.com.asb.mdms.base.web.action;

import java.util.Enumeration;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.com.asb.mdms.base.util.query.QueryInfo;
import cn.com.asb.mdms.common.log.MyLogger;
import cn.com.asb.mdms.common.util.StringUtil;

public abstract class BaseFreeDispatchAction extends DispatchAction {

	protected Logger log = MyLogger.getLog(getClass().getName());

	private static ApplicationContext ctx = null;

	public Object getBean(String name) {
		if (ctx == null) {
			ctx = WebApplicationContextUtils
			.getRequiredWebApplicationContext(servlet.getServletContext());
		}
		return ctx.getBean(name);
	}
	
	public String getDisplayTagParam(HttpServletRequest request, String regex) {
		Enumeration en = request.getParameterNames();
		while (en.hasMoreElements()) {
			String name = (String) en.nextElement();
			if (name.matches(regex)) {
				return request.getParameter(name);
			}
		}
		return null;
	}

	protected ActionForward findActionForwardWithParams(ActionMapping mapping, String forwardName, Map params) {
		ActionForward forwardFromXml = mapping.findForward(forwardName);
		String path = forwardFromXml.getPath();
		log.debug("old path : " + path );
		try {
			path = StringUtil.replaceParams4UrlPath(path ,params);
			log.debug("new path : " + path );
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		ActionForward forward = new ActionForward(path);
		forward.setRedirect(forwardFromXml.getRedirect());
		return forward;
	}

	protected void fillMapWithoutEmptyValue(QueryInfo info, String key, Object value) {
		fillMapWithoutEmptyValue(info,key,value,"");
	}
	
	protected void fillMapWithoutEmptyValue(QueryInfo info, String key, Object value,String ignoreValue) {
		if(StringUtil.isNotNullObject(value) && !ignoreValue.equals(value.toString()))
			info.getQueryParameters().put(key, value);
	}
}
